package com.devenv.controller;

import com.devenv.dto.*;
import com.devenv.service.UserService;
import com.devenv.util.JwtUtil;
import com.devenv.common.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;

/**
 * 认证控制器 - 开源版
 * 基于开发版AuthController精简实现
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class AuthController {

    private final UserService userService;
    private final JwtUtil jwtUtil;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<UserDTO> register(@Valid @RequestBody RegisterRequest request) {
        try {
            UserDTO user = userService.register(request);
            return Result.success(user, "注册成功");
        } catch (IllegalArgumentException e) {
            log.warn("用户注册失败: {}", e.getMessage());
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return Result.error("注册失败: " + e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest request, 
                                     HttpServletRequest httpRequest) {
        try {
            String clientIp = getClientIp(httpRequest);
            LoginResponse response = userService.login(request, clientIp);
            log.info("用户登录成功: username={}", request.getUsername());
            return Result.success(response, "登录成功");
        } catch (IllegalArgumentException e) {
            log.warn("用户登录失败: {}", e.getMessage());
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("用户登录失败", e);
            return Result.error("登录失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public Result<UserDTO> getCurrentUser(@RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.replace("Bearer ", "");
            String username = jwtUtil.getUsernameFromToken(token);
            UserDTO user = userService.getUserByUsername(username);
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取当前用户信息失败", e);
            return Result.unauthorized("获取用户信息失败");
        }
    }

    /**
     * 刷新token
     */
    @PostMapping("/refresh")
    public Result<LoginResponse> refreshToken(@RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.replace("Bearer ", "");
            
            // 验证token有效性（即使过期也要能解析用户名）
            String username = jwtUtil.getUsernameFromExpiredToken(token);
            UserDTO user = userService.getUserByUsername(username);
            
            // 生成新token
            String newToken = jwtUtil.generateToken(username, user.getId());
            LoginResponse response = new LoginResponse(newToken, jwtUtil.getExpiration(), user);
            
            return Result.success(response, "Token刷新成功");
        } catch (Exception e) {
            log.error("Token刷新失败", e);
            return Result.unauthorized("Token刷新失败");
        }
    }

    /**
     * 获取客户端IP
     */
    private String getClientIp(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0];
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}
